package com.dubito.composenote.ui.screen

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldColors
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.dubito.composenote.ComposeNoteApp
import com.dubito.composenote.Constants
import com.dubito.composenote.R
import com.dubito.composenote.model.Note
import com.dubito.composenote.ui.composable.GenericAppBar
import com.dubito.composenote.ui.composable.NotesFloatingActionButton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * author: LiLiang
 * createTime: 2022/10/6-18:24
 * remark:
 **/

@Composable
fun NoteEditScreen(noteId: Int, navController: NavController, viewModel: NoteViewModel) {
    val scope = rememberCoroutineScope()
    var note by remember {
        mutableStateOf(Constants.noteDetailPlaceHolder)
    }
    var currentNote by remember {
        mutableStateOf(note.note)
    }
    var currentTitle by remember {
        mutableStateOf(note.title)
    }
    var currentImageUri by remember {
        mutableStateOf(note.imageUri)
    }
    val saveButtonState = remember {
        mutableStateOf(false)
    }

    val getImageRequest = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument(),
        onResult = { uri ->
            uri?.let {
                ComposeNoteApp.getUriPermission(uri)
                currentImageUri = uri.toString()
                if (currentImageUri != note.imageUri) {
                    saveButtonState.value = true
                }
            }
        }
    )

    LaunchedEffect(key1 = true) {
        scope.launch(Dispatchers.IO) {
            note = viewModel.getNote(noteId) ?: Constants.noteDetailPlaceHolder
            currentNote = note.note
            currentTitle = note.title
            currentImageUri = note.imageUri
        }
    }

    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
        Scaffold(
            topBar = {
                GenericAppBar(
                    title = stringResource(id = R.string.edit),
                    onIconClick = {
                        viewModel.updateNote(
                            Note(
                                id = note.id,
                                note = currentNote,
                                title = currentTitle,
                                imageUri = currentImageUri
                            )
                        )
                        navController.popBackStack()
                    },
                    icon = {
                        Icon(
                            imageVector = Icons.Default.AddCircle,
                            contentDescription = stringResource(R.string.save),
                            tint = Color.Black
                        )
                    },
                    iconState = saveButtonState
                )
            },
            floatingActionButton = {
                NotesFloatingActionButton(
                    contentDescription = stringResource(R.string.add_image),
                    action = {
                        getImageRequest.launch(arrayOf("image/*"))
                    },
                    icon = Icons.Filled.Add
                )
            }
        ) { paddingValues ->
            Column(
                modifier = Modifier
                    .padding(paddingValues)
                    .fillMaxSize()
            )
            {
                currentImageUri?.let {
//                    AsyncImage(model = Uri.parse(it), contentDescription = "")
                    Image(
                        painter = rememberAsyncImagePainter(
                            model = ImageRequest
                                .Builder(LocalContext.current)
                                .data(data = Uri.parse(it))
                                .build()
                        ),
                        contentDescription = "",
                        modifier = Modifier
                            .fillMaxHeight(0.3f)
                            .fillMaxWidth()
                            .padding(6.dp),
                        contentScale = ContentScale.Crop
                    )
                }
                TextField(
                    value = currentTitle, colors = TextFieldDefaults.textFieldColors(
                        cursorColor = Color.Black,
                        focusedLabelColor = Color.Black
                    ),
                    onValueChange = { value ->
                        currentTitle = value
                        if (currentTitle != note.title) {
                            saveButtonState.value = true
                        } else if (currentNote == note.note && currentTitle == note.title) {
                            saveButtonState.value = false
                        } else {
                            saveButtonState.value = false
                        }
                    },
                    label = {
                        Text(text = stringResource(R.string.title))
                    }
                )
                Spacer(modifier = Modifier.height(12.dp))
                TextField(
                    value = currentNote, colors = TextFieldDefaults.textFieldColors(
                        cursorColor = Color.Black,
                        focusedLabelColor = Color.Black
                    ),
                    onValueChange = { value ->
                        currentNote = value
                        if (currentNote != note.note) {
                            saveButtonState.value = true
                        } else if (currentNote == note.note && currentTitle == note.title) {
                            saveButtonState.value = false
                        } else {
                            saveButtonState.value = false
                        }
                    },
                    label = {
                        Text(text = stringResource(R.string.body))
                    }
                )
            }
        }
    }

}